﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using Ultima;
using SpellCaster3.Forms;
using SpellCaster3.Core;
using System.Xml.Serialization;
using System.IO;
using Expand;
using Expand.Linq;
using Expand.Patterns.Command;
using Commands = SpellCaster3.Commands;
using System.Net;

namespace SpellCaster3
{
    public partial class HomeForm : Form
    {
        // On Toolstrip

        private void nuovoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ShouldSave)
                if (MessageBox.Show("Il profilo è stato modificato, vuoi salvarlo?", "Attenzione", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                    salvaToolStripMenuItem_Click(sender, e);

            SpellCasterManager.CurrentProfile = new Profile();
            SpellCasterManager.CurrentProfilePath = string.Empty;
            LoadProfile(SpellCasterManager.CurrentProfile);
        }

        private void apriToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ShouldSave)
                if (MessageBox.Show("Il profilo è stato modificato, vuoi salvarlo?", "Attenzione", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                    salvaToolStripMenuItem_Click(sender, e);

            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                try
                {
                    SpellCasterManager.Load(openFileDialog.FileName);
                    LoadProfile(SpellCasterManager.CurrentProfile);
                }
                catch (FileNotFoundException)
                {
                    ErrorForm.Show("File non valido o non trovato");
                }
                catch (Exception loadException)
                {
                    ErrorForm.Show("Apertura del file fallita probabilmente per un formato errato", loadException);
                }
            }
        }

        private void salvaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(SpellCasterManager.CurrentProfilePath))
            {
                salvaconnomeToolStripMenuItem_Click(sender, e);
                return;
            }
            SaveProfile(SpellCasterManager.CurrentProfilePath);
        }

        private Control GetFocusedControl()
        {
            Control focusedControl = null;
            foreach (Control control in iconSettingsGroupBox.Controls)
            {
                if (control.Focused)
                {
                    focusedControl = control;
                    break;
                }
            }
            return focusedControl;
        }

        private void copiaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!iconsListBox.Focused)
            {
                Control focusedControl = GetFocusedControl();
                if (focusedControl != null)
                    if (focusedControl.GetType() == (typeof(TextBox)))
                        Clipboard.SetText((focusedControl as TextBox).SelectedText);
                return;
            }

            if (iconsListBox.SelectedItems.Count < 1)
            {
                ErrorForm.Show("Necessario selezionare almeno un dato da copiare");
                return;
            }

            ButtonMacro[] tmp = new ButtonMacro[iconsListBox.SelectedItems.Count];
            int i = 0;
            foreach (ButtonMacro macro in iconsListBox.SelectedItems)
            {
                tmp[i] = macro;
                ++i;
            }
            Clipboard.SetData(tmp.GetType().FullName, tmp);
        }

        private void incollaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!iconsListBox.Focused)
            {
                Control focusedControl = GetFocusedControl();
                if (focusedControl != null)
                    if (focusedControl.GetType() == (typeof(TextBox)))
                        if (Clipboard.ContainsText())
                        {
                            string firstPart = (focusedControl as TextBox).Text.Substring(0, (focusedControl as TextBox).SelectionStart);
                            string secondPart = (focusedControl as TextBox).Text.Substring((focusedControl as TextBox).SelectionStart + (focusedControl as TextBox).SelectionLength);

                            (focusedControl as TextBox).Text = firstPart + Clipboard.GetText() + secondPart;
                            (focusedControl as TextBox).SelectionStart = (firstPart + Clipboard.GetText()).Length;
                            (focusedControl as TextBox).SelectionLength = 0;
                        }
                return;
            }

            string errorMsg = "Dati presenti nella clipboard non validi per l'operazione";
            IDataObject data = Clipboard.GetDataObject();

            if (!data.GetDataPresent(typeof(ButtonMacro[]).FullName))
            {
                ErrorForm.Show(errorMsg);
                return;
            }

            ButtonMacro[] tmp = data.GetData(typeof(ButtonMacro[]).FullName) as ButtonMacro[];

            if (tmp == null)
            {
                ErrorForm.Show(errorMsg);
                return;
            }

            History.BeginCompoundDo();
            foreach (ButtonMacro macro in tmp)
                History.Do(new Commands.InsertButtonMacroCommand(this, macro, SpellCasterManager.CurrentProfile.ButtonsMacro, SpellCasterManager.CurrentProfile.ButtonsMacro.Count));
            History.EndCompundDo();
        }

        private void annullaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            History.Undo();
        }

        private void ripristinaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            History.Redo();
        }

        // On Menu

        private void salvaconnomeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                SpellCasterManager.CurrentProfilePath = saveFileDialog.FileName;
                SaveProfile(SpellCasterManager.CurrentProfilePath);
            }
        }

        private void esciToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!Visible)
                Restore();
            Close();
        }

        private void opzioniToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (Form frm = new OptionsForm())
                frm.ShowDialog(this);
        }

        private void informazionisuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (AboutBox about = new AboutBox())
                about.ShowDialog(this);
        }

        private void selezionatuttoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < iconsListBox.Items.Count; ++i)
                iconsListBox.SetSelected(i, true);
        }

        private void mostraToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Restore();
        }

        private void HomeForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ShouldSave)
                if (MessageBox.Show("Il profilo è stato modificato, vuoi salvarlo?", "Attenzione", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                    salvaToolStripMenuItem_Click(sender, e);
        }

        private void controllaAggiornamentiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Defaults
            Version curVer = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            string updateAddress = @"http://dl.dropbox.com/u/762638/Files/Documents/My%20Programs/SpellCaster3/";

            try
            {
                try
                {
                    updateAddress = File.ReadAllText(System.IO.Path.GetDirectoryName(Application.ExecutablePath) + System.IO.Path.DirectorySeparatorChar + "update.cfg");
                }
                catch (Exception) { }

                using (WebClient client = new WebClient())
                {
                    string res = client.DownloadString(updateAddress + "version.txt");
                    Version newVer = Version.Parse(res);
                    if (newVer > curVer)
                    {
                        if (MessageBox.Show("Nuova versione del programma, vuoi scaricarla?", "Informazione", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            try
                            {
                                System.Diagnostics.Process.Start(updateAddress + "setup_" + newVer.ToString() + ".zip");
                            }
                            catch (Exception) { }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Nessun aggiornamento trovato", "Informazione", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Problemi nella ricerca di aggiornamenti, riprovare più tardi", "Attenzione", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            ButtonMacro tmp = new ButtonMacro();
            Point newPosition = new Point(0, 0);
            newPosition.X = Location.X - 44;
            newPosition.Y = Location.Y;
            tmp.Position = newPosition;

            History.Do(new Commands.InsertButtonMacroCommand(this, tmp, SpellCasterManager.CurrentProfile.ButtonsMacro, SpellCasterManager.CurrentProfile.ButtonsMacro.Count));
            iconsListBox.ClearSelected();
            iconsListBox.SelectedIndex = iconsListBox.Items.Count - 1;
        }

        private void deleteButton_Click(object sender, EventArgs e)
        {
            History.BeginCompoundDo();
            foreach (int i in iconsListBox.SelectedIndices)
            {
                History.Do(new Commands.RemoveButtonMacroCommand(this, SpellCaster3.SpellCasterManager.CurrentProfile.ButtonsMacro[i], SpellCasterManager.CurrentProfile.ButtonsMacro, i));
            }
            History.EndCompundDo();
            iconsListBox.ClearSelected();
        }

        private void importaProfiloSpellCaster20ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ShouldSave)
                if (MessageBox.Show("Il profilo è stato modificato, vuoi salvarlo?", "Attenzione", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                    salvaToolStripMenuItem_Click(sender, e);

            if (importSpellCaster20FileDialog.ShowDialog(this) == DialogResult.OK)
            {
                try
                {
                    Tuple<Profile, string> result = Core.Importer.ImportManager.Import(importSpellCaster20FileDialog.FileName);
                    if (!string.IsNullOrWhiteSpace(result.Item2))
                        MessageBox.Show("Le seguenti icone usano un'immagine assente nello SpellCaster3, verrà usata la prima disponibile:\n\n" + result.Item2, "Attenzione", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    Profile p = result.Item1;
                    SpellCasterManager.CurrentProfile = p;
                    LoadProfile(SpellCasterManager.CurrentProfile);
                    SpellCasterManager.CurrentProfilePath = string.Empty;
                    SpellCasterManager.UndoSaveCommandsAmount = -1;
                    UpdateUndoRedoButtons(null, null);
                }
                catch (Exception excp)
                {
                    ErrorForm.Show("Problemi nell'importazione del profilo", excp);
                }
            }
        }

        private void visualizzaGuidaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (Form frm = new GuideForm())
                frm.ShowDialog(this);
        }

        private void RecentProfileClick(object sender, EventArgs e)
        {
            int index = fileRecentiToolStripMenuItem.DropDownItems.IndexOf(sender as ToolStripItem);
            if (index < 0)
                ErrorForm.Show(@"Si è verificato un problema nel rintracciare il file di profilo, caricarlo manualmente perfavore");
            else
            {
                if (ShouldSave)
                    if (MessageBox.Show("Il profilo è stato modificato, vuoi salvarlo?", "Attenzione", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                        salvaToolStripMenuItem_Click(sender, e);

                try
                {
                    SpellCasterManager.Load(SpellCaster3.Properties.Settings.Default.RecentProfiles[index]);
                    LoadProfile(SpellCasterManager.CurrentProfile);
                }
                catch (FileNotFoundException)
                {
                    ErrorForm.Show("File non valido o non trovato");
                }
                catch (Exception loadException)
                {
                    ErrorForm.Show("Apertura del file fallita probabilmente per un formato errato", loadException);
                }
            }
        }
    }
}
